const ejs = require('ejs');
const fs = require('fs');
class Html {
  constructor(config) {
    const { template } = config;
    this.template = template;
    this.htmlTemplate = undefined;
    this.outputPath = undefined;
  }

  async loadTemplate() {
    if (this.htmlTemplate) {
      return;
    }
    const templateStr = await new Promise((res, rej) => {
      fs.readFile(this.template, 'utf-8', (err, data) => {
        if (err) {
          return rej(err);
        }
        return res(data);
      });
    });
    this.htmlTemplate = ejs.compile(
      templateStr,
      // { debug: true },
    );
  }

  getAdapterInstance() {
    return this.htmlTemplate;
  }

  async generate(data, outputPath) {
    await this.loadTemplate();
    const html = this.htmlTemplate(data);
    await new Promise((res, rej) => {
      fs.writeFile(outputPath, html, (err) => {
        if (err) {
          return rej(err);
        }
        return res();
      });
    });
    this.outputPath = outputPath;
    return outputPath;
  }
}

module.exports = Html;
